package tcp_proxy_middleware

import (
	"fmt"
	"strings"

	"gin-gateway/core/utils"
	"gin-gateway/reverse_proxy"
)

func TCPFlowLimitMiddleware() func(c *reverse_proxy.TcpSliceRouterContext) {
	return func(c *reverse_proxy.TcpSliceRouterContext) {
		serviceDetail := GetServiceDetail(c)

		// 服务限流
		if serviceDetail.AccessControl.ServiceFlowLimit != 0 {
			serviceLimiter, err := utils.FlowLimitManager.GetLimiter(utils.FlowServicePrefix+serviceDetail.Info.ServiceName,
				float64(serviceDetail.AccessControl.ServiceFlowLimit))
			if err != nil {
				c.Conn.Write([]byte(err.Error()))
				c.Abort()
				return
			}
			if !serviceLimiter.Allow() {
				c.Conn.Write([]byte(fmt.Sprintf("service flow limit %v", serviceDetail.AccessControl.ServiceFlowLimit)))
				c.Abort()
				return
			}
		}

		clientIP := strings.Split(c.Conn.RemoteAddr().String(), ":")[0]

		// ip 限流
		if serviceDetail.AccessControl.ClientIPFlowLimit > 0 {
			clientIpLimiter, err := utils.FlowLimitManager.GetLimiter(utils.FlowServicePrefix+serviceDetail.Info.ServiceName+"_"+clientIP,
				float64(serviceDetail.AccessControl.ClientIPFlowLimit))
			if err != nil {
				c.Conn.Write([]byte(err.Error()))
				c.Abort()
				return
			}
			if !clientIpLimiter.Allow() {
				c.Conn.Write([]byte(fmt.Sprintf("%v flow limit %v", clientIP, serviceDetail.AccessControl.ClientIPFlowLimit)))
				c.Abort()
				return
			}
		}
		c.Next()
	}
}
